<template>
  <div class="cart-list-container">
    <div class="header">
      <h2 class="cart-title">我的购物车</h2>
      <el-button @click="$router.push('/')" type="primary" size="small">
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
    </div>

    <div v-if="cartStore.loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <template v-else>
      <div v-for="cart in cartList" :key="cart.cartId" class="cart-item">
        <el-table
          :data="cart.cartItemList"
          style="width: 100%"
          border
          :header-cell-style="{ textAlign: 'center' }"
          :cell-style="{ textAlign: 'center' }"
        >
          <el-table-column prop="bookName" label="图书名称">
            <template #default="{ row }">
              <div class="book-info">
                <el-image
                  v-if="row.book?.cover"
                  :src="row.book.cover"
                  :preview-src-list="[row.book.cover]"
                  fit="cover"
                  class="book-cover"
                />
                <span class="book-name">{{ row.bookName }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="price" label="单价" width="120">
            <template #default="{ row }">
              <span class="price">¥{{ Number(row.price).toFixed(2) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="数量" width="180">
            <template #default="{ row }">
              <div class="quantity-control">
                <el-button
                  size="small"
                  @click="handleQuantityDecrease(cart.cartId, row)"
                  :disabled="row.quantity <= 1"
                >
                  -
                </el-button>
                <span class="quantity-display">{{ row.quantity }}</span>
                <el-button
                  size="small"
                  @click="handleQuantityIncrease(cart.cartId, row)"
                  :disabled="row.quantity >= 99"
                >
                  +
                </el-button>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="小计" width="120">
            <template #default="{ row }">
              <span class="subtotal">¥{{ calculateSubtotal(row).toFixed(2) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row.bookId)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="cart-footer">
          <div class="cart-summary">
            <span class="total-label">小计：</span>
            <span class="total-amount">¥{{ calculateCartTotal(cart).toFixed(2) }}</span>
          </div>
        </div>
      </div>

      <div v-if="cartList.length > 0" class="checkout-footer">
        <div class="total-summary">
          <span class="total-label">总计：</span>
          <span class="total-amount">¥{{ totalAmount.toFixed(2) }}</span>
        </div>
        <el-button
          type="primary"
          size="large"
          :loading="checkoutLoading"
          @click="handleCheckoutAll"
        >
          全部结算
        </el-button>
      </div>

      <el-empty
        v-if="cartList.length === 0"
        description="购物车是空的"
      >
        <el-button type="primary" @click="$router.push('/books')">
          去选购图书
        </el-button>
      </el-empty>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { useCartStore } from '@/stores/cart'
import type { Cart, CartItem } from '@/types/cart'

const router = useRouter()
const cartStore = useCartStore()
const checkoutLoading = ref(false)

// 处理后端返回的购物车数据
const cartList = computed(() => {
  console.log('Cart data:', cartStore.cartList)
  return cartStore.cartList
})

// 计算单个商品小计
const calculateSubtotal = (item: CartItem) => {
  return Number(item.price) * item.quantity
}

// 计算单个购物车总金额
const calculateCartTotal = (cart: Cart) => {
  return cart.cartItemList.reduce((total, item) => {
    return total + calculateSubtotal(item)
  }, 0)
}

// 计算所有购物车总金额
const totalAmount = computed(() => {
  return cartList.value.reduce((total, cart) => {
    return total + calculateCartTotal(cart)
  }, 0)
})

// 处理数量变化
const handleQuantityChange = async (cartId: number, bookId: number, newQuantity: number) => {
  if (!bookId || cartStore.updateLoading) return

  try {
    const success = await cartStore.updateCartItem(cartId, bookId, newQuantity)
    if (!success) {
      ElMessage.error('更新数量失败，请重试')
    }
  } catch (error) {
    console.error('更新数量失败:', error)
    ElMessage.error('更新数量失败，请重试')
  }
}

// 处理减少数量
const handleQuantityDecrease = async (cartId: number, cartItem: CartItem) => {
  if (cartItem.quantity <= 1 || cartStore.updateLoading) return
  await handleQuantityChange(cartId, cartItem.bookId, cartItem.quantity - 1)
}

// 处理增加数量
const handleQuantityIncrease = async (cartId: number, cartItem: CartItem) => {
  if (cartItem.quantity >= 99 || cartStore.updateLoading) return
  await handleQuantityChange(cartId, cartItem.bookId, cartItem.quantity + 1)
}

const handleDelete = async (bookId: number | undefined) => {
  if (!bookId) {
    ElMessage.error('删除失败：图书ID不存在')
    return
  }

  try {
    await ElMessageBox.confirm(
      '确定要从购物车中删除该图书吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const success = await cartStore.removeFromCart(bookId)
    if (success) {
      ElMessage.success('删除成功')
    }
  } catch (error) {
    console.error('删除失败:', error)
    // 用户取消删除操作时不显示错误提示
    if (error !== 'cancel') {
      ElMessage.error('删除失败，请重试')
    }
  }
}

const handleCheckoutAll = async () => {
  if (cartList.value.length === 0) {
    ElMessage.warning('购物车是空的')
    return
  }

  try {
    await ElMessageBox.confirm(
      '确定要结算所有商品吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    checkoutLoading.value = true
    // 遍历所有购物车进行结算
    for (const cart of cartList.value) {
      await cartStore.checkout(cart.cartId)
    }
    router.push('/orders')
  } catch {
    // 用户取消结算操作
  } finally {
    checkoutLoading.value = false
  }
}

onMounted(() => {
  cartStore.fetchCartList()
})
</script>

<style scoped>
.cart-list-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.cart-title {
  margin: 0;
}

.loading-container {
  padding: 20px;
}

.cart-item {
  margin-bottom: 24px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.cart-item:last-child {
  margin-bottom: 16px;
}

.book-info {
  display: flex;
  align-items: center;
  text-align: left;
}

.book-cover {
  width: 60px;
  height: 80px;
  margin-right: 12px;
  border-radius: 4px;
  object-fit: cover;
}

.book-name {
  font-size: 14px;
  color: #303133;
}

.price, .subtotal {
  color: #f56c6c;
  font-weight: 600;
}

.cart-footer {
  margin-top: 0;
  padding: 16px 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  background: #f8f9fa;
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
}

.cart-summary {
  display: flex;
  align-items: center;
}

.checkout-footer {
  margin-top: 24px;
  padding: 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.total-summary {
  margin-right: 24px;
}

.total-label {
  font-size: 16px;
  color: #606266;
  margin-right: 8px;
}

.total-amount {
  font-size: 20px;
  font-weight: 600;
  color: #f56c6c;
}

.quantity-control {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.quantity-display {
  min-width: 40px;
  text-align: center;
  font-size: 14px;
  color: #606266;
}

:deep(.el-button.is-disabled) {
  cursor: not-allowed;
}
</style>
